package com.zjs.jsp.fdservice.tasks;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjs.jsp.domain.jsp.Jsp_Order;
import com.zjs.jsp.domain.jsp.Jsp_Task;
import com.zjs.jsp.fdservice.service.SendJspTask;
import com.zjs.jsp.fdservice.service.mongodb.JspTaskExpand;
import com.zjs.jsp.fdservice.service.mongodb.JspTaskRepository;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 未下发订单处理
 *
 * @author 李文
 * @create 2017-09-04 9:25
 **/
@Component
public class ScheduledTasks
{

    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledTasks.class);
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Autowired
    private JspTaskExpand jspTaskExpand;

    @Autowired
    private JspTaskRepository jspTaskRepository;

    @Autowired
    private RedissonClient client;

    @Autowired
    private SendJspTask sendJspTask;

    /**
     * 30秒执行一次
     */
    @Scheduled(cron = "0/30 * *  * * ? ")
    public void reportCurrentTime() {
        List<String> pkList = jspTaskExpand.getPk();
        for (String pk : pkList) {
            LOGGER.info(" 当前处理的 厅点是 " + pk);
            if (StringUtils.isEmpty(pk)) {
                continue;
            }
            RLock pkLock = client.getLock("rt" + pk);
            // 判断厅点是否上锁  上锁就放弃
            if (pkLock.isLocked()) {
                continue;
            }
            try {
                pkLock.lock(2, TimeUnit.MINUTES);
                List<Jsp_Task> jspTasks = jspTaskRepository.findByPkAndXfzt(pk, 0);
                for (Jsp_Task task : jspTasks) {
                    LOGGER.info(" task " + task.toString());
                    long minute = System.currentTimeMillis() - task.getDate().getTime();
                    long d = minute / 1000;
                    LOGGER.info("  时间 " + d);
                    if (task.getOd().size() >= task.getZd() || d >= task.getDdjs()) {
                        LOGGER.info(" 条件成功 ");
                        //  发送数据到MQ
                        Jsp_Order jsp_order = new Jsp_Order();
                        String strBody = OBJECT_MAPPER.writeValueAsString(task);
                        sendJspTask.sendMqData(strBody, jsp_order, null, task);
                    } else {
                        LOGGER.info(" 条件没成功 ");
                    }
                }
            } catch (Exception e) {
                LOGGER.error(" 定时任务出行异常  当前厅点编号： " + pk, e);
            } finally {
                // 解锁
                pkLock.unlock();
            }
        }
    }
}